import router from './router'
import store from './store'

router.beforeEach(async(to, form, next) => {
  const token = store.getters.token
  const url = to.path
  const whiteListr = ['/login', '/404']

  // 有登录去登录页
  if (token && url === '/login') {
    next('/')
  }
  // 有登陆去其他页
  if (token && url !== '/login') {
    if (!store.state.user.userInfo.username) {
      await store.dispatch('user/getUserInfo')
      const routes = await store.dispatch('permission/filterMents', store.state.user.userInfo.roles.menus)
      // console.log(routes)
      router.addRoutes([
        ...routes,
        { path: '*', redirect: '/404', hidden: true }
      ])
      next(to.path)
    } else {
      next()
    }
  }
  // 没登录去白名单
  if (!token && whiteListr.indexOf(url) > -1) {
    next()
  }
  // 没登录去其他页
  if (!token && whiteListr.indexOf(url) === -1) {
    next('/login')
  }
  // 第二种用法
//   if (store.getters.token) {
//     //  已登录
//     if (to.path === '/login') {
//       next('/')
//     } else {
//       next()
//     }
//   } else {
//     // 未登录
//     const whiteListr = ['/login', '/404']
//     if (whiteListr.indexOf(to.path) > -1) {
//       next()
//     } else {
//       next('/login')
//     }
//   }
})
